# ES6 模块化 export & import

# 基本导入导出

HTML 中引入 JS 时需要注明 type 属性值为 module,声明每个文件都是单独一个模块(此时使用var都不会产生全局变量问题),否则无法导入

# default 导入导出

  • 某些情况下,一个模块中包含某个功能需要导出,但我们并不希望给这个功能命名,希望让导入者自己来命名
  • default 在同一个模块中只能有一个

# * 导入

希望将某个模块的所以信息都导入,一个个写很麻烦,可以使用 * 导入,并起别名

# 综合示例

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- HTML 中引入 JS 时需要注明 type 属性值为 module,声明每个文件都是单独一个模块 -->
    <script src="./js/utils.js" type="module"></script>
    <script src="./js/main.js" type="module"></script>
    <script src="./js/poem.js" type="module"></script>
  </body>
</html>

导出

// ./js/utils.js

// 导出方式1:直接写在 变量、函数、类等之前
/**
 * 每年的天数
 */
export const DAY_OF_YEAR = 365;

/**
 * 格式化时间
 * @param {Date} date
 */
function formatDate(date) {
  return `${date.getFullYear()}-${
    date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1
  }-${date.getDate() < 10 ? "0" + date.getDate() : date.getDate()} ${
    date.getHours() < 10 ? "0" + date.getHours() : date.getHours()
  }:${date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()}:${
    date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds()
  }`;
}

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  say() {
    console.log("姓名:" + this.name + ",年龄:" + this.age);
  }
}

function add(num1, num2) {
  console.log(num1 + "+" + num2 + "=" + (num1 + num2));
}

// 导出方式2(推荐)
export { formatDate, Person };

// default导出,也可以直接写在变量、函数、类等之前
export default add;
// ./js/poem.js

const SPRING =
  "天街小雨润如酥,草色遥看近却无。最是一年春好处,绝胜烟柳满皇都。";
const SUMMER =
  "毕竟西湖六月中,风光不与四时同。接天莲叶无穷碧,映日荷花别样红。";
const AUTUMN =
  "银烛秋光冷画屏,轻罗小扇扑流萤。天阶夜色凉如水,坐看牵牛织女星。";
const WINTER = "日暮苍山远,天寒白屋贫。柴门闻犬吠,风雪夜归人。";

export { SPRING, SUMMER, AUTUMN, WINTER };

导入

// ./js/main.js

// 都可以使用 as 起别名(default导入的直接就可以自定义名称,且导入的只有一个)
import plus, {
  formatDate as format,
  DAY_OF_YEAR as DAY,
  Person,
} from "./utils.js";

// 统一全部导入
import * as poem from "./poem.js";

console.log(DAY);

console.log(format(new Date()));

const student = new Person("张三", 13);
student.say();

plus(1, 2);

console.log(poem.AUTUMN);